package fr.android.exia.assassin.classes;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import fr.android.exia.assassin.R;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class TropheeAdapter extends BaseAdapter{

	ArrayList<Trophee> trophees;
	LayoutInflater inflater;
	
	public TropheeAdapter(Context ctx, JSONArray jsonArray) {
		inflater = LayoutInflater.from(ctx);
		trophees = new ArrayList<Trophee>();
		
		for (int i=0; i< jsonArray.length(); i++) {
			try {
				JSONObject pq = jsonArray.getJSONObject(i);
				Trophee t = new Trophee(" 1 "+pq.getString("nom"), pq.getString("urlimage"));
				this.trophees.add(t);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
        	
        }
	}
	
	public int getCount() {
		return this.trophees.size();
	}

	public Object getItem(int arg0) {
		return this.trophees.get(arg0);
	}

	public long getItemId(int arg0) {
		return arg0;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		
		if(convertView == null) {
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.itemtrophee, null);
			holder.nom = (TextView)convertView.findViewById(R.id.tvNom);
			holder.image = (ImageView)convertView.findViewById(R.id.ivObjet);
			convertView.setTag(holder);			
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		holder.nom.setText(trophees.get(position).nom);
		Drawable drawage = LoadImageFromWebOperations(trophees.get(position).urlimage);
		holder.image.setImageDrawable(drawage);
		
		return convertView;
	}
	
	private Drawable LoadImageFromWebOperations(String url)
    {
      try{
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, "src name");
        return d;
      }catch (Exception e) {
        System.out.println("Exc="+e);
        return null;
      }
    }

}


class ViewHolder {
	TextView nom;
	ImageView image;
}
